package com.totoro.job;

import com.totoro.controller.AdminController;
import com.totoro.controller.RegisterFormController;
import com.totoro.pojo.*;
import com.totoro.service.*;
import com.totoro.utils.TimeIntervalUtil;
import lombok.extern.log4j.Log4j;
import org.apache.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author TOTORO
 * @date 2021/7/26 20:40
 */
@Component
@DisallowConcurrentExecution // 不允许并发执行
public class Quartz {
    static Logger logger = Logger.getLogger(Quartz.class);

    @Autowired
    AdminController adminController;
    @Autowired
    UserService userService;
    @Autowired
    OrderService orderService;
    @Autowired
    EvaluationService evaluationService;
    @Autowired
    ShopService shopService;
    @Autowired
    SellerService sellerService;
    @Autowired
    ProductService productService;

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final String ADMIN = "[订单清道夫] ";
    private static final Integer AUTOMATIC_DAY = 15, AUTOMATIC_MINUTE = 15;
    private static final String TITLE = "准备开始清扫订单了！！！  -  ";

    static {
        logger.warn("任务调度框架已启动！");
    }

    /**
     * 未付款订单15分钟自动关闭
     */
    @Scheduled(cron="0/20 * *  * * ? ")
    public void automaticCloeOrder(){
        logger.warn(ADMIN + TITLE+simpleDateFormat.format(new Date()));
        List<MarketOrder> orderList = orderService.findAllOrder(null, 3, 1);
        if(orderList != null && orderList.size() > 0){
            orderList.forEach(toto ->{
                boolean isReach = TimeIntervalUtil.isReach(toto.createTime, AUTOMATIC_MINUTE, TimeIntervalUtil.MINUTE);
                if(isReach){
                    // 添加一条订单关闭的时间轴
                    OrderTimeline orderTimeline = new OrderTimeline(0, toto.getId(), 8);
                    orderService.addOrderTimeLineByMid(orderTimeline);
                    // 改变订单状态，添加时间线
                    toto.setOrderStatus(8);
                    orderService.updateOrder(toto);
                    // 如果这次订单的商品是拍下减库存，则加回去
                    toto.getMarketSrOrderList().forEach(ro ->{
                        Product product = productService.findProductById(ro.getProduct().getId());
                        if(product.getItMethod() == 0){
                            productService.updateProductStock(0, ro.getBuyCount(), product.getId());
                            productService.updateSkuGroupStock(0, ro.getBuyCount(), ro.getSkuCode());
                        }
                    });
                    logger.warn(ADMIN+"这次我清理了"+orderList.size()+"个未付款的订单哦！ (自动关闭)");
                }
            });
        }
    }

    /**
     * 15天自动收货
     */
    @Scheduled(cron="0/120 * *  * * ? ")
    public void automaticReceiptOrder(){
        logger.warn(ADMIN + TITLE+simpleDateFormat.format(new Date()));
        List<MarketOrder> orderList = orderService.findAllOrder(null, 3, 3);
        if(orderList != null && orderList.size() > 0){
            // 如果已经过了十五天
            orderList.forEach(toto ->{
                boolean isReach = TimeIntervalUtil.isReach(toto.createTime, AUTOMATIC_DAY, TimeIntervalUtil.DAY);
                if(isReach){
                    // 添加一条已收货的时间轴
                    OrderTimeline orderTimeline = new OrderTimeline(0, toto.getId(), 4);
                    orderService.addOrderTimeLineByMid(orderTimeline);
                    // 改变订单状态，添加时间线
                    toto.setOrderStatus(4);
                    orderService.updateOrder(toto);
                    logger.warn(ADMIN+"这次我清理了"+orderList.size()+"个未收货的订单哦！(确认收货)");
                }
            });
        }
    }

    /**
     * 15天自动好评
     */
    @Scheduled(cron="0/120 * *  * * ? ")
    public void automaticGoodEvaluationOrder(){
        logger.warn("评价"+ADMIN + TITLE+simpleDateFormat.format(new Date()));
        // 获得每个总订单，进行迭代
        List<MarketOrder> orderList = orderService.findAllOrder(null, 3, 4);
        if(orderList != null && orderList.size() > 0){
            orderList.forEach(toto ->{
                boolean isReach = TimeIntervalUtil.isReach(toto.createTime, AUTOMATIC_DAY, TimeIntervalUtil.DAY);
                System.out.println(isReach);
                if(isReach){
                    // 添加一条已评价的时间轴
                    OrderTimeline orderTimeline = new OrderTimeline(0, toto.getId(), 5);
                    orderService.addOrderTimeLineByMid(orderTimeline);
                    // 改变主订单状态
                    toto.setOrderStatus(5);
                    orderService.updateOrder(toto);
                    System.out.println(toto.getMarketSrOrderList().size());
                    toto.getMarketSrOrderList().forEach(ro ->{
                        // 如果有详情订单未评论
                        if(ro.getIsComment() == 0){
                            ProductComment productComment = new ProductComment(toto.getUser().getUserId(), toto.getShop().getSeller().getId(), ro.getId(), "totoro yyds", 1, 5, 5, 5, 0, 1);
                            // 作出好评
                            evaluationService.addProductComment(productComment);
                            // 修改评论状态
                            orderService.updateMarketSrOrderCommentStatus(ro.getId());
                            // 修改卖家的积分，店铺的积分
                            shopService.updateShopStar(productComment);
                            sellerService.updateSellerScore(productComment.getCommentScore(), productComment.getSlid());
                            Shop shop = shopService.findShopBySlid(productComment.getSlid());
                        }
                    });
                    logger.warn(ADMIN+"这次我清理了"+toto.getMarketSrOrderList().size()+"个未评价的订单哦 (自动好评)");
                }
            });
        }
    }

    /**
     * 清除管理员登录验证码
     */
    @Scheduled(cron="0/40 * *  * * ? ")
    public void clearCode(){
        // 找到所有超时三分钟的验证码
        long threeMinuteL = 180000L;
        Map<String, PhoneCode> codeMap = adminController.getCodeMap();
        if(null != codeMap && codeMap.size()>0){
            codeMap.forEach((k,v)->{
                long interval = System.currentTimeMillis() - v.getCreateTime().getTime();
                if(interval>=threeMinuteL){
                    codeMap.remove(k);
                }
            });
        }
    }

    /**
     * 增加日用户数量，每天凌晨一次
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void addDayUserCount(){
        String nowDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        UserOnline userOnline = userService.findDayUserOnline(new UserOnline(0,1,0,nowDate, nowDate));
        if(null == userOnline) {
            userService.addUserOnlineCount(1);
        }
    }

    /**
     * 给每个商品添加一个月成交0每月一号执行一次
     */
    @Scheduled(cron = "0 0 0 1 */1 ?")
    public void addProductMonthDeal(){
        Integer[] productIds = productService.findAllProductId();
        productService.addProductMonthDeal(productIds);
    }
}
